<template>
  <div class="image-cropper">
    <vue-cropper
      ref="cropperRef"
      :img="imageUrl"
      :autoCrop="true"
      :fixedBox="false"
      :centerBox="true"
      :canMoveBox="true"
      :info="true"
      outputType="png"
    />
    <div style="margin-bottom: 16px" />
    <!-- 图片操作 -->
    <div class="image-cropper-actions">
      <el-button @click="rotateLeft">向左旋转</el-button>
      <el-button @click="rotateRight">向右旋转</el-button>
      <el-button @click="changeScale(1)">放大</el-button>
      <el-button @click="changeScale(-1)">缩小</el-button>
      <el-button @click="crop" :loading="cropping" type="primary">裁剪</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { uploadPictureAPI } from '@/api/pictureAPI'

const props = defineProps(['imageUrl', 'picture', 'spaceId'])
const emits = defineEmits(['cropSuccess'])

// 编辑器组件的引用
const cropperRef = ref()
// 向左旋转
const rotateLeft = () => {
  cropperRef.value.rotateLeft()
}

// 向右旋转
const rotateRight = () => {
  cropperRef.value.rotateRight()
}

// 缩放
const changeScale = (num) => {
  cropperRef.value.changeScale(num)
}

// 裁剪
const cropping = ref(false)

// 裁剪
const crop = async () => {
  cropperRef.value.getCropBlob((blob) => {
    const fileName = (props.picture?.name || 'image') + '.png'
    const file = new File([blob], fileName, { type: blob.type })
    // 上传图片
    handleUpload({ file })
  })
}

/**
 * 上传
 * @param file
 */
const handleUpload = async ({ file }) => {
  cropping.value = true
  const params = props.picture ? { id: props.picture.id } : {}
  params.spaceId = props.spaceId
  const res = await uploadPictureAPI(file, params)
  console.log('剪切上传成功', res)

  emits('cropSuccess', res.data)
  cropping.value = false
}
</script>

<style scoped>
.image-cropper {
  text-align: center;
}

.image-cropper .vue-cropper {
  height: 400px;
}
</style>
